import { connection } from "../util/mysql.mjs"; 
import  querystring from 'querystring'
const control = (req,res)=>{
      const reg = /[?/]{1}/g
      const urlArr = req.url.split(reg)
      if(urlArr.indexOf('query')!==-1){
        queryMethod(req,res)
      }    
      else if(urlArr.indexOf('add')!==-1){
        insertMethod(req,res)
      }  
      else if(urlArr.indexOf('update')!==-1){
        updateMethod(req,res)
      }
      else if(urlArr.indexOf('delete')!==-1){
        deleteMethod(req,res)
      }
    }
const queryMethod = (req,res)=>{
    const selectQuery = 'SELECT * FROM USER';
    connection.query(selectQuery, (err, results) => {
        if (err) {
          console.error('Error querying data:', err);
          return;
        }
        else{
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify(results));
        }
      });
}
const insertMethod = (req,res)=>{
  let parsedBody = null;
    if (req.method === 'POST') {
        let body = '';
        req.on('data', (chunk) => {
            body += chunk.toString();
        });
        
        req.on('end', () => {
            parsedBody = querystring.parse(body);
            tryAdd(parsedBody)
        });
    }
    function tryAdd(parsedBody){
        let {age,name,org,sex} = parsedBody;
        if(age&&name&&org&&sex){
          const insertQuery = 'INSERT INTO USER SET ? ';
          connection.query(insertQuery, {age,name,org,sex}, (err, result) => {
              if (err) {
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({message:  'Error inserting data'}));
              }
              else{
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({message:  'User added successfully'}));
              }
          });
        }
        else{
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({message:  'Invalid data'}));
        }
    }
}
const updateMethod = (req,res)=>{
    let parsedBody = null;
    if (req.method === 'POST') {
      let body = '';
      req.on('data', (chunk) => {
          body += chunk.toString();
      });
      req.on('end', () => {
          parsedBody = querystring.parse(body);
          tryUpdate(parsedBody)
      });
    }
    function tryUpdate(parsedBody){
      const {id,name,age,org,sex} = parsedBody;
      const updateQuery = 'UPDATE USER SET ? WHERE id =?';
      connection.query(updateQuery, [{name,age,org,sex,id}, id], (err, result) => {
        if (err) {
          console.error('Error updating data:', err);
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({message:  'Error update data'}));
        }
        else{
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({message:  'success update data'}));
        }
      });
    }
}
const deleteMethod = (req,res)=>{
    let parsedBody = null;
    if (req.method === 'POST') {
        let body = '';
        req.on('data', (chunk) => {
            body += chunk.toString();
        });
        
        req.on('end', () => {
            parsedBody = querystring.parse(body);
            tryDelete(parsedBody)
        });
    }  
    function tryDelete(parsedBody){
        let {id} = parsedBody;
        if(id){
          const deleteQuery = 'DELETE FROM USER WHERE id =?';
          connection.query(deleteQuery, [id], (err, result) => {
            if (err) {
              console.error('Error deleting data:', err);
              res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({message:  'User delete err'}));
            }
            else{
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify({message:  'User delete successfully'}));
            }
          });
        }
        else{
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({message:  'Invalid data'}));
        }

  }
}
export  { control };